/*
 * TOP SECRET Copyright 2006-2015 Transsion.com All right reserved. This software is the confidential and proprietary
 * information of Transsion.com ("Confidential Information"). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you entered into with Transsion.com.
 */
package com.yunji.framework_template.common.http;

import java.io.IOException;

import org.apache.commons.httpclient.HttpException;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;

import com.yunji.framework_template.common.util.StringUtil;
import com.yunji.framework_template.common.web.HttpResult;

/**
 * ClassName:JsoupUtil <br/>
 * Date: 2019年1月17日 下午2:20:46 <br/>
 * 
 * @author fenglibin1982@163.com
 * @Blog http://blog.csdn.net/fenglibing
 * @version
 * @see
 */
public class JsoupUtil {

    /**
     * 根据URL获取其内容，并以Jsoup Element的方式返回
     * 
     * @param url
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static Element getPageElement(String url) throws HttpException, IOException {
        HttpResult result = HttpClientUtil.doGet(url);
        if (result == null || result.getCode() != 200 || StringUtil.isEmpty(result.getContent())) {
            return null;
        }
        Element element = new Element(Tag.valueOf("contents"), url);
        element.html(result.getContent());
        return element;
    }

    /**
     * 将Element中所有图片的地址更新为绝对地址
     * 
     * @param element
     */
    public static void updateImgSrcToAbsolute(Element element) {
        Elements imgElements = element.select("img");
        if (!imgElements.isEmpty()) {
            for (int i = 0; i < imgElements.size(); i++) {
                Element imgElement = imgElements.get(i);
                String absImgHref = imgElement.absUrl("src");
                imgElement.attr("src", absImgHref);
            }
        }

        Elements aElements = element.select("a");
        if (!aElements.isEmpty()) {
            for (int i = 0; i < aElements.size(); i++) {
                Element aElement = aElements.get(i);
                String aHref = aElement.absUrl("href");
                if (aHref != null && (aHref.endsWith(".jpg") || aHref.endsWith(".png"))) {// 是图片链接
                    String absAHref = aElement.absUrl("href");
                    aElement.attr("href", absAHref);
                }
            }
        }
    }
}
